package com.smartcampusbackend.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.smartcampusbackend.util.FileUploadUtil;
import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
public class FileController {

    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> upload(@RequestParam("file") MultipartFile file) {
        Map<String, Object> resp = new HashMap<>();
        try {
            if (file.getSize() > 50 * 1024 * 1024) {
                resp.put("code", 400);
                resp.put("message", "文件大小不能超过50MB");
                return ResponseEntity.badRequest().body(resp);
            }
            String uploadDir = "uploads";
            File dir = new File(uploadDir);
            if (!dir.exists()) dir.mkdirs();

            String originalFilename = file.getOriginalFilename();
            String ext = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                ext = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID().toString() + ext;
            String filePath = uploadDir + File.separator + fileName;
            Files.copy(file.getInputStream(), Paths.get(filePath));

            resp.put("code", 200);
            resp.put("message", "上传成功");
            resp.put("url", "/uploads/" + fileName);
            return ResponseEntity.ok(resp);
        } catch (Exception e) {
            resp.put("code", 500);
            resp.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(resp);
        }
    }

    /**
     * 通用文件下载接口，支持多级路径
     */
    @GetMapping("/download/**")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取多级路径
            String uri = request.getRequestURI();
            String prefix = "/api/download/";
            int idx = uri.indexOf(prefix);
            String filePath = uri.substring(idx + prefix.length()); // attachments/xxx.docx

            File file = new File("uploads" + File.separator + filePath);
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            String originalFileName = file.getName();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" +
                    URLEncoder.encode(originalFileName, "UTF-8") + "\"");
            response.setHeader("Content-Length", String.valueOf(file.length()));
            Files.copy(file.toPath(), response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("下载失败: " + e.getMessage());
            } catch (IOException ex) {
                // 忽略
            }
        }
    }

    /**
     * 职称评审附件下载
     */
    @GetMapping("/title-attachment/{fileName}")
    public void downloadTitleAttachment(@PathVariable String fileName, HttpServletResponse response) {
        try {
            String filePath = "uploads" + File.separator + fileName;
            File file = new File(filePath);
            
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 设置响应头强制下载
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + 
                URLEncoder.encode(fileName, "UTF-8") + "\"");
            response.setHeader("Content-Length", String.valueOf(file.length()));

            Files.copy(file.toPath(), response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("下载失败: " + e.getMessage());
            } catch (IOException ex) {
                // 忽略
            }
        }
    }
} 